package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listTree() {
        //获取所有分类数据
        List<CategoryEntity> allEntities = baseMapper.selectList(null);
        List<CategoryEntity> categoryEntityList = allEntities.stream().filter(categoryEntity -> {
            //找出一级分类
            return categoryEntity.getParentCid() == 0;
        }).map(categoryEntity -> {
            //遍历一级分类的每一个对象，去设置子目录
            categoryEntity.setChildren(getChild(categoryEntity,allEntities));
            return categoryEntity;
        }).sorted((categoryEntity1,categoryEntity2)->{
            return (categoryEntity1.getSort()==null?0:categoryEntity1.getSort())-(categoryEntity2.getSort()==null?0:categoryEntity2.getSort());
        }).collect(Collectors.toList());

        return categoryEntityList;


    }

    @Override
    public void deleteMenu(List<Long> asList) {
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths=new ArrayList<>();
        List<Long> parentPath = this.findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

        @CacheEvict(value = "category",key = "'getLevel1Category'")
    @Override
    public void updateByIdCascade(CategoryEntity category) {
        CategoryEntity oldcate = baseMapper.selectById(category.getCatId());
        String oldcateName = oldcate.getName();
        this.updateById(category);
        String name = category.getName();
        if (!name.equals(oldcateName)){
            categoryBrandRelationService.updateCate(category);
        }

    }

  /*  1、每一个需要缓存的数据，我们需要指定放到哪个名字的缓存（最好按照业务划分名字）
      2、代表当前方法的结果需要缓存，缓存中没有，放入缓存。缓存中已经存在，方法不调用
      3、默认行为
        1、如果没有 执行方法，缓存中有，不执行
        2、key默认自动生成，缓存的名字 category1::SimpleKey []
        3、value的值为 默认使用jdk序列化机制，把结果序列化后，存入redis
        4、默认ttl时间为-1
      自定义操作
        1、指定生成缓存的key名称  key属性指定 可以使用spel语法
        2、指定存活时间 spring.cache.redis.time-to-live
        3、value的值为json格式

    */
    @Cacheable(value = "category",key = "#root.methodName")

    @Override
    public List<CategoryEntity> getLevel1Category() {

        List<CategoryEntity> categoryEntities = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatelog() {
        System.out.println("查询了数据库");
        List<CategoryEntity> level1Category = this.getLevel1Category();
        //获取到所有的一级分类id
        Map<String, List<Catelog2Vo>> map = level1Category.stream().collect(Collectors.toMap(l1 -> l1.getCatId().toString(),
                l1 -> {
                    List<Catelog2Vo> catelog2VoList = null;
                    Long l1CatId = l1.getCatId();
                    List<CategoryEntity> catelog2List = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", l1CatId));
                    catelog2VoList = catelog2List.stream().map(l2 -> {
                        Catelog2Vo catelog2Vo = new Catelog2Vo();
                        catelog2Vo.setCatalog1Id(l1CatId.toString());
                        catelog2Vo.setId(l2.getCatId().toString());
                        catelog2Vo.setName(l2.getName());

                        //根据二级分类id查三级分类
                        List<CategoryEntity> catelog3List = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                        List<Catelog2Vo.Catelog3Vo> catelog3VoList = catelog3List.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo();
                            catelog3Vo.setCatalog2Id(l2.getCatId().toString());
                            catelog3Vo.setId(l3.getCatId().toString());
                            catelog3Vo.setName(l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());

                        catelog2Vo.setCatalog3List(catelog3VoList);
                        return catelog2Vo;
                    }).collect(Collectors.toList());

                    return catelog2VoList;
                }));
        return map;
    }

    //    @Override
    public Map<String, List<Catelog2Vo>> getCatelog1() {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String catelog2 = ops.get("catelog2");
        if (StringUtils.isEmpty(catelog2)){
            System.out.println("缓存没命中，查询数据库");
            Map<String, List<Catelog2Vo>> catelogToDB = getCatelogToDBWithRedisLock();
            return catelogToDB;
        }
        System.out.println("缓存命中，直接返回");
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catelog2, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;
    }

    public Map<String, List<Catelog2Vo>> getCatelogToDBWithRedisLock() {
            //占分布式锁 并且设置过期时间，要求加锁和设置过期时间为原子性操作
        String uuid = UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid,300, TimeUnit.SECONDS);
        if (lock){
            System.out.println("获取分布式锁成功。。。");
            Map<String, List<Catelog2Vo>> dataToDB = getDataToDB();
            //删除分布式锁 要求也是原子操作
            String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                    "    return redis.call(\"del\",KEYS[1])\n" +
                    "else\n" +
                    "    return 0\n" +
                    "end";
            stringRedisTemplate.execute(new DefaultRedisScript<Long>(script,Long.class),Arrays.asList("lock"),uuid);
            return dataToDB;
        }else {
            System.out.println("获取分布式锁失败。。等待重试");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatelogToDBWithRedisLock();
        }


    }

    private Map<String, List<Catelog2Vo>> getDataToDB() {
        //再进行一次查询缓存
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String catelog2 = ops.get("catelog2");
        if (!StringUtils.isEmpty(catelog2)) {
            //缓存命中 直接返回
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catelog2, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }
        System.out.println("查询了数据库");
        List<CategoryEntity> level1Category = this.getLevel1Category();
        //获取到所有的一级分类id
        Map<String, List<Catelog2Vo>> map = level1Category.stream().collect(Collectors.toMap(l1 -> l1.getCatId().toString(),
                l1 -> {
                    List<Catelog2Vo> catelog2VoList = null;
                    Long l1CatId = l1.getCatId();
                    List<CategoryEntity> catelog2List = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", l1CatId));
                    catelog2VoList = catelog2List.stream().map(l2 -> {
                        Catelog2Vo catelog2Vo = new Catelog2Vo();
                        catelog2Vo.setCatalog1Id(l1CatId.toString());
                        catelog2Vo.setId(l2.getCatId().toString());
                        catelog2Vo.setName(l2.getName());

                        //根据二级分类id查三级分类
                        List<CategoryEntity> catelog3List = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                        List<Catelog2Vo.Catelog3Vo> catelog3VoList = catelog3List.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo();
                            catelog3Vo.setCatalog2Id(l2.getCatId().toString());
                            catelog3Vo.setId(l3.getCatId().toString());
                            catelog3Vo.setName(l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());

                        catelog2Vo.setCatalog3List(catelog3VoList);
                        return catelog2Vo;
                    }).collect(Collectors.toList());

                    return catelog2VoList;
                }));

        String s = JSON.toJSONString(map);
        ops.set("catelog2", s);
        return map;
    }

    public Map<String, List<Catelog2Vo>> getCatelogToDBWithLocalLock() {

        synchronized (this){
            //在进行一次查询缓存
            return getDataToDB();
        }
    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        paths.add(catelogId);
        CategoryEntity categoryEntity = baseMapper.selectById(catelogId);
        Long parentCid = categoryEntity.getParentCid();
        if (parentCid!=0){
            this.findParentPath(parentCid,paths);
        }
        return paths;
    }

    private List<CategoryEntity> getChild(CategoryEntity root,List<CategoryEntity> all){

        List<CategoryEntity> child = all.stream().filter(categoryEntity -> {
            //1、找到所有分类对象中 每一个一级分类对应的二级分类集合 # 4、找到二级分类对象中的三级分类 #7、找到三级分类中的子节点，发现为空
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {//2、遍历每一个二级分类 # 5、遍历每一个三级分类
            //3、把二级分类传进去，设置二级分类的三级分类 #6、把三级分类传进去，设置三级分类的子节点
            categoryEntity.setChildren(getChild(categoryEntity,all));
            return categoryEntity;
        }).sorted((c1,c2)->{
            return (c1.getSort()==null?0:c1.getSort())-(c2.getSort()==null?0:c2.getSort());
        }).collect(Collectors.toList());
        return child;
    }

}